<template>
  <page-view class="search-food">
    <page-header title="搜索" :show-back="true"></page-header>
    <div class="content-box">
      <div class="query-box">
        <input
          type="text"
          class="query-text"
          placeholder="请输入菜品名称"
          v-model="keyword"
        />
        <button class="query-btn" @click="getFood($event)">搜索</button>
      </div>
      <div class="search-result-box" v-if="foodList.length > 0">
        <van-list
          :loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <food-item
            v-for="(item, index) in foodList"
            :key="index"
            :f_item="item"
          ></food-item>
        </van-list>
      </div>
    </div>
  </page-view>
</template>

<script setup>
import foodItem from "../components/FoodItem.vue";
import { ref, reactive } from "vue";
import api from "../utils/api";
import { showFailToast } from "vant";

const keyword = ref("");

const loading = ref(false);
const finished = ref(false);
const pageIndex = ref(1);
const foodList = reactive([]);
const totalPage = ref(0);
const getFood = async (e) => {
  if (e) {
    finished.value = false;
    pageIndex.value = 1;
    foodList.length = 0;
  }

  if (keyword.value.trim() === "") return showFailToast("搜索不能为空");

  let result = await api.foodInfo.findByPage({
    pageIndex: pageIndex.value,
    food_name: keyword.value,
  });
  // console.log(result);
  totalPage.value = result.totalPage;
  result.list.map((item) => {
    item.food_img = item.food_img.split(",");
    foodList.push(item);
  });
  loading.value = false;
  finished.value = pageIndex.value >= totalPage.value;
};

const onLoad = () => {
  if (pageIndex.value < totalPage.value) {
    pageIndex.value++;
    getFood();
  }
};
</script>

<style lang="scss" scoped>
.search-food {
  @include flexbox(column);
  .content-box {
    flex: 1;
    overflow: auto;
    @include flexbox(column);
    .query-box {
      width: 80%;
      height: 30px;
      margin: 10px auto;
      border-radius: 30px;
      overflow: hidden;
      display: flex;
      border: 1px solid skyblue;
      .query-text {
        flex: 1;
        border: none;
        padding: 0px 10px;
        background-color: #fff;
      }
      .query-btn {
        border: none;
        width: 45px;
        background-color: lightgray;
      }
    }
    .search-result-box {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>